<?php

namespace app\admin\controller\baiduwebtongji;

use app\common\controller\Backend;
use addons\baiduwebtongji\library\TongjiApi;

/**
 * 百度网站统计-Api接口
 */
class Baiduapi extends Backend
{
    protected $noNeedRight = ['getOutline','trendTimeA','getTimeTrendRpt','getCommonTrackRpt','trendLatestA','sourceAll','sourceSearchword','visitToppage','visitDistrict','visitWorld','visitDistrictTop','rankGetData','rankGetWords','rankSetWords'];
    public function _initialize()
    {
        parent::_initialize();
        set_time_limit(10);
        session_write_close();
        $this->config = get_addon_config('baiduwebtongji');
        $this->visit = new TongjiApi($this->config);
    }
    public function getOutline()
    {
        $data=$this->visit->getOutline();
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $result=$data['body']['data'][0]['result'];
            if($result){
                $html='';
                $items=$result['items'];
                foreach ($items as $key => $value) {
                    if($key==0){
                        $html.='<tr class="highlight">';
                    }else{
                        if($key>2){
                            $html.='<tr class="getoutline-fade toggleable-hidden">';
                        }else{
                            $html.='<tr>';
                        }
                    }
                    if($key==2){
                        $arrow_up1=$this->switchFlag($items[2][1]['flag']);
                        $arrow_up2=$this->switchFlag($items[2][2]['flag']);
                        $arrow_up3=$this->switchFlag($items[2][3]['flag']);
                    }else{
                        $arrow_up1=$arrow_up2=$arrow_up3='';
                    }
                    $html.='<td class="no-top-border normal">'.$value[0].'</td>';
                    $html.='<td class="no-top-border '.$arrow_up1.'">'.(is_array($value[1])?$value[1]['val']:$value[1]).'</td>';
                    $html.='<td class="no-top-border '.$arrow_up2.'">'.(is_array($value[2])?$value[2]['val']:$value[2]).'</td>';
                    $html.='<td class="no-top-border '.$arrow_up3.'">'.(is_array($value[3])?$value[3]['val']:$value[3]).'</td>';
                    $html.='<td class="no-top-border">'.(is_array($value[4])?($value[4]['val']=="--"?$value[4]['val']:$value[4]['val']."%"):($value[4]=="--"?$value[4]:$value[4]."%")).'</td>';
                    $html.='<td class="no-top-border">'.(is_array($value[5])?$this->Sec2Time($value[5]['val']):$this->Sec2Time($value[5])).'</td>';
                    $html.='<td class="no-top-border">'.(is_array($value[6])?$value[6]['val']:$value[6]).'</td>';
                    $html.='</tr>';
                    if($key==5){
                        unset($value[0]);
                        $html.='<tr class="getoutline-fade toggleable-hidden">';
                        $html.='<td class="no-top-border normal"></td>';
                        foreach ($value as $k => $v) {
                            $html.='<td class="no-top-border">';
                            if(is_array($v)){
                                $html.=$v['date'];
                            }else{
                                $html.='--';
                            }
                            $html.='</td>';
                        }
                        $html.='</tr>';
                    }
                    if($key==2){
                        $html.='<tr class="empty-tr1"></tr>';
                        $html.='<tr class="getoutline-fade empty-tr2 toggleable-hidden"><td colspan="7"></td></tr>';
                    }
                }
                $html.='<tr class="getoutline-fade empty-tr3 toggleable-hidden"><td colspan="7"></td></tr>';
                $res=[
                    'status'=>1,
                    'html'=>$html
                ];
                unset($result);
                return $res;
            }
        }
        $res=[
            'status'=>0,
            'msg'=>'<tr><td colspan="10" style="text-align:center;">暂无数据</td></tr>'
        ];
        return $res;
    }
    /**
     * [trendTimeA 趋势分析]
     * @return [type] [description]
     */
    public function trendTimeA(){
        $data=$this->visit->trendTimeA();
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $result=$data['body']['data'][0]['result'];
            if($result){
                $pv_count=$result['sum'][0][0];
                $visitor_count=$result['sum'][0][1];
                $data['pv_count']=$pv_count;
                $data['visitor_count']=$visitor_count;
                unset($result);
                $res=[
                    'status'=>1,
                    'data'  =>$data
                ];
                return $res;
            }
        }
        $res=[
            'status'=>0
        ];
        return $res;
    }
    public function getTimeTrendRpt(){
        $memo=input("post.memo")?:'week';
        $dateRange=$this->getStartEndDate($memo);
        $start_date=$dateRange['start_date'];
        $end_date=$dateRange['end_date'];
        $data=$this->visit->getTimeTrendRpt($start_date,$end_date);
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $result=$data['body']['data'][0]['result'];
            if($result){
                foreach ($result['items'][0] as $key => $value) {
                    $data['date'][$key]=$value[0];
                }
                foreach ($result['items'][1] as $ke => $val) {
                    $data['pv'][$ke]=$val[0]=='--'?0:$val[0];
                    $data['uv'][$ke]=$val[1]=='--'?0:$val[1];
                }
                $data['timeSpan']=$result['timeSpan'][0];
                $res=[
                    'status'=>1,
                    'data'=>$data
                ];
                unset($result);
                return $res;
            }
        }
        $res=[
            'status'=>0
        ];
        return $res;
    }
    /**
     * [getCommonTrackRpt 搜索词、来源网站、入口界面、受访页面、新老访客]
     * @return [type] [description]
     */
    public function getCommonTrackRpt(){
        $memo=input("post.memo")?:'tody';
        $dateRange=$this->getStartEndDate($memo);
        $start_date=$dateRange['start_date'];
        $end_date=$dateRange['end_date'];
        $data=$this->visit->getCommonTrackRpt($start_date,$end_date);
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $result=$data['body']['data'][0]['result'];
            if($result){
                $data['sourceSite']=$data['word']=$data['landingPage']=$data['visitPage']='';
                foreach ($result['sourceSite']['items'] as $key => $value) {
                    $data['sourceSite'].='<tr><td class="no-borders al"><span class="ellipsis" title="'.$value[0].'">'.$value[0].'</span></td>';
                    $data['sourceSite'].='<td class="no-borders text-right">'.$value[1].'</td>';
                    $data['sourceSite'].='<td class="no-borders ratio"><div title="'.$value[2].'%" style="background-color:#DCEBFE; width:'.$value[2].'%;">'.$value[2].'%</div></td></tr>';
                }
                foreach ($result['word']['items'] as $key => $value) {
                    $data['word'].='<tr><td class="no-borders al"><span class="ellipsis" title="'.$value[0].'">'.$value[0].'</span></td>';
                    $data['word'].='<td class="no-borders text-right">'.$value[1].'</td>';
                    $data['word'].='<td class="no-borders ratio"><div title="'.$value[2].'%" style="background-color:#DCEBFE; width:'.$value[2].'%;">'.$value[2].'%</div></td></tr>';
                }
                foreach ($result['landingPage']['items'] as $key => $value) {
                    $data['landingPage'].='<tr><td class="no-borders al"><a href="'.$value[0].'" target="_blank" class="ellipsis" title="'.$value[0].'">'.$value[0].'</a></td>';
                    $data['landingPage'].='<td class="no-borders text-right">'.$value[1].'</td>';
                    $data['landingPage'].='<td class="no-borders ratio"><div title="'.$value[2].'%" style="background-color:#DCEBFE; width:'.$value[2].'%;">'.$value[2].'%</div></td></tr>';
                }
                foreach ($result['visitPage']['items'] as $key => $value) {
                    $data['visitPage'].='<tr><td class="no-borders al"><a href="'.$value[0].'" target="_blank" class="ellipsis" title="'.$value[0].'">'.$value[0].'</a></td>';
                    $data['visitPage'].='<td class="no-borders text-right">'.$value[1].'</td>';
                    $data['visitPage'].='<td class="no-borders ratio"><div title="'.$value[2].'%" style="background-color:#DCEBFE; width:'.$value[2].'%;">'.$value[2].'%</div></td></tr>';
                }
                $data['visitType']=$result['visitType'];
                $data['visitType']['oldVisitor']['avg_visit_time']=$this->Sec2Time($data['visitType']['oldVisitor']['avg_visit_time']);
                $data['visitType']['newVisitor']['avg_visit_time']=$this->Sec2Time($data['visitType']['newVisitor']['avg_visit_time']);
                unset($result);
                $res=[
                    'status'=>1,
                    'data'=>$data
                ];
                return $res;
            }
        }
        $res=[
            'status'=>0
        ];
        return $res;
    }
    /*
    public function getDistrict(){
        $param=[
            'metrics'       =>  'pv_count,visitor_count',
            'max_results'   =>  10,
            'start_date'    =>  date("Ymd",strtotime("-6 day")),
            'end_date'      =>  date("Ymd"),
        ];
        $getDistrict=$this->visit->visitDistrict($param);
        if($getDistrict){
            foreach ($getDistrict['items'][0] as $key => $value) {
                $data['area'][$key]=$value[0]['name'];
            }
            foreach ($getDistrict['items'][1] as $ke => $val) {
                $data['pv'][$ke]=$val[0];
                $data['uv'][$ke]=$val[1];
            }
            $data['timeSpan']=$getDistrict['timeSpan'][0];
            unset($getDistrict);
            $res=[
                'status'=>1,
                'data'=>$data
            ];
        }else{
            $res=[
                'status'=>0
            ];
        }
        return $res;
    }
    */
    /**
     * 实时访客
     */
    public function trendLatestA(){
        $page=input("page")?:1;
        $max_results=20;
        $data=$this->visit->trendLatestA($page,$max_results);
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $result=$data['body']['data'][0]['result'];
            if($result){
                $html='';
                $list=$result['items'][1];
                foreach ($list as $key => $value) {
                    $detail=$result['items'][0][$key][0]['detail'];
                    $html.='<tr>';
                    $html.='<td><div class="td-content"><a href="javascript:;" class="show-detail" data-key="'.$key.'"><i class="fa fa-plus" aria-hidden="true"></i></a></div></td>';
                    $html.='<td><div class="td-content">'.(20*($page-1)+$key+1).'</div></td>';
                    $html.='<td><div class="td-content">'.$value[0].'</div></td>';
                    $html.='<td><div class="td-content">';
                    $html.='<span title="'.$value[1].'">'.$value[1].'</span>';
                    $html.='</div></td>';
                    $html.='<td><div class="td-content">';
                    if(isset($value[2]['url'])){
                        $html.='<a href="'.$value[2]['url'].'" target="_blank" title="'.$value[2]['url'].'">'.$value[2]['fromType'].'</a>';
                    }else{
                        $html.=$value[2]['fromType'];
                    }
                    $html.='</div></td>';
                    $html.='<td><div class="td-content"><a href="'.$value[3].'" target="_blank" title="'.$value[3].'">'.$value[3].'</a></div></td>';
                    $html.='<td><div class="td-content">'.$value[4].'</div></td>';
                    $html.='<td><div class="td-content">'.$value[5].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$this->Sec2Time($value[6]).'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[7].'</div></td>';
                    $html.='</tr>';
                    $html.='<tr class="table_tr_'.$key.' sub-line sub-line-first sub-line-last">';
                    $html.='<td colspan="10" class="detail sub-title no-indent">';
                    $html.='<div class="td-content">';
                    $html.='<span class="icon"></span>';
                    $html.='<div class="visitor-detail clearfix">';
                    $html.='<div class="client-info l">';
                    $html.='<div class="device-info">';
                    $html.='<div class="device-icon l"><div class="'.$detail['osType'].'"></div></div>';
                    $html.='<div class="device-data l">';
                    $html.='<ul class="attributes">';
                    if($detail['os']){
                        $html.='<li title="'.$detail['os'].'"><span class="detail-title">操作系统：</span>'.$detail['os'].'</li>';
                    }
                    if($detail['isp']){
                        $html.='<li title="'.$detail['isp'].'"><span class="detail-title">网络服务商：</span>'.$detail['isp'].'</li>';
                    }
                    if($detail['resolution']){
                        $html.='<li title="'.$detail['resolution'].'"><span class="detail-title">屏幕分辨率：</span>'.$detail['resolution'].'</li>';
                    }
                    if($detail['color']){
                        $html.='<li title="'.$detail['color'].'"><span class="detail-title">屏幕颜色：</span>'.$detail['color'].'</li>';
                    }
                    $html.='</ul></div></div>';
                    $html.='<div class="browser-info">';
                    $html.='<div class="browser-icon l">';
                    $html.='<div class="'.$detail['browserType'].'"></div>';
                    $html.='</div>';
                    $html.='<div class="browser-data l">';
                    $html.='<ul class="attributes">';
                    if($detail['browser']){
                        $html.='<li title="'.$detail['browser'].'"><span class="detail-title">浏览器：</span>'.$detail['browser'].'</li>';
                    }
                    if($detail['cookie']){
                        $html.='<li title="'.$detail['cookie'].'"><span class="detail-title">是否支持Cookie：</span>'.$detail['cookie'].'</li>';
                    }
                    if($detail['java']){
                        $html.='<li title="'.$detail['java'].'"><span class="detail-title">是否支持JAVA：</span>'.$detail['java'].'</li>';
                    }
                    $html.='</ul></div></div></div>';
                    $html.='<div class="user-info">';
                    $html.='<div class="user-icon l"></div>';
                    $html.='<div class="user-data">';
                    $html.='<ul class="visitor-type">';
                    $html.='<li><span class="detail-title">访问类型：</span>'.$detail['visitorType'].'</li>';
                    $html.='<li><span class="detail-title">当天访问频次：</span>'.$detail['visitorFrequency'].'</li>';
                    $html.='<li><span class="detail-title">上一次访问时间：</span>'.$detail['lastVisitTime'].'</li>';
                    $html.='<li><span class="detail-title">本次来路：</span>'.$detail['fromType']['fromType'].'</li>';
                    $html.='<li><span class="detail-title">入口页面：<a href="'.$detail['accessPage'].'" title="'.$detail['accessPage'].'" target="_blank">'.$detail['accessPage'].'</a></span></li>';
                    $html.='<li><span class="detail-title">最后停留在：<a href="'.$detail['endPage'].'" title="'.$detail['endPage'].'" target="_blank">'.$detail['endPage'].'</a></span></li>';
                    $html.='</ul></div></div>';
                    $html.='<div class="path-info"><table><tbody><tr class="path-title">';
                    $html.='<td style="width: 5em; padding-right: 18px;">访问路径：</td>';
                    $html.='<td style="width: 5em; padding-left: 0px;">打开时间</td>';
                    $html.='<td style="width: 5em; text-align: right;">停留时长</td>';
                    $html.='<td>页面地址</td></tr>';
                    foreach ($detail['paths'] as $k => $paths) {
                        $html.='<tr><td style="width: 5em; padding-right: 0px;"></td>';
                        $html.='<td style="width: 5em; padding: 0px;">'.$paths[0].'</td>';
                        $html.='<td style="text-align: right;">'.$this->Sec2Time($paths[1]).'</td>';
                        $html.='<td><a href="'.$paths[2].'" title="'.$paths[2].'" target="_blank">'.$paths[2].'</a></td></tr>';
                    }
                    $html.='</tbody></table></div></div></div></td></tr>';
                }
                $total=$result['total'];
                $page = \think\paginator\driver\Bootstrap::make(null, $max_results,$page, $total, false, ['path'=>request()->url()]);
                $res=[
                    'status'=>1,
                    'page'=>$this->ajax_page($page),
                    'html'=>$html
                ];
                return $res;
            }
        }
        $res=[
            'status'=>0,
            'msg'=>'暂无数据'
        ];
        return $res;
    }

    public function sourceAll(){
        $page=input("post.page")?:1;
        $memo=input("post.memo")?:'tody';
        $dateRange=$this->getStartEndDate($memo);
        $start_date=$dateRange['start_date'];
        $end_date=$dateRange['end_date'];
        $max_results=20;
        $data=$this->visit->sourceAll($page,$max_results,$start_date,$end_date);
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $result=$data['body']['data'][0]['result'];
            if($result){
                $html='';
                $list=$result['items'][1];
                foreach ($list as $key => $value) {
                    $value[3]=$value[3]=='--'?0:$value[3];
                    $html.='<tr>';
                    $html.='<td><div class="td-content">'.(20*($page-1)+$key+1).'</div></td>';
                    $html.='<td><div class="td-content">'.$result['items'][0][$key][0]['name'].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[0].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[1].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[2].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[3].'%</div></td>';
                    $html.='<td><div class="td-content text-right">'.$this->Sec2Time($value[4]).'</div></td>';
                    $html.='</tr>';
                }
                $result['sum'][0][3]=$result['sum'][0][3]=='--'?0:$result['sum'][0][3];
                $html.='<tr>';
                $html.='<td><div class="td-content"></div></td>';
                $html.='<td><div class="td-content">当前汇总</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][0].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][1].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][2].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][3].'%</div></td>';
                $html.='<td><div class="td-content text-right">'.$this->Sec2Time($result['pageSum'][0][4]).'</div></td>';
                $html.='</tr>';
                $total=$result['total'];
                if($total>$max_results){
                    $page = \think\paginator\driver\Bootstrap::make(null, $max_results,$page, $total, false, ['path'=>request()->url()]);
                    $page=$this->ajax_page_memo($page,$memo);
                }else{
                    $page='';
                }
                $sum=$result['sum'][0];
                $sum[3]=$sum[3]=='--'?0:$sum[3];
                $sum[4]=$this->Sec2Time($sum[4]);
                $res=[
                    'status'=>1,
                    'page'=>$page,
                    'html'=>$html,
                    'sum'=>$sum
                ];
                return $res;
            }
        }
        $res=[
            'status'=>0,
            'msg'=>'暂无数据'
        ];
        return $res;
    }

    public function sourceSearchword(){
        $page=input("post.page")?:1;
        $memo=input("post.memo")?:'tody';
        $dateRange=$this->getStartEndDate($memo);
        $start_date=$dateRange['start_date'];
        $end_date=$dateRange['end_date'];
        $max_results=20;
        $data=$this->visit->sourceSearchword($page,$max_results,$start_date,$end_date);
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $sourceSearchword=$data['body']['data'][0]['result'];
            if($sourceSearchword){
                $html='';
                $list=$sourceSearchword['items'][1];
                foreach ($list as $key => $value) {
                    $value[3]=$value[3]=='--'?0:$value[3];
                    $html.='<tr>';
                    $html.='<td><div class="td-content">'.(20*($page-1)+$key+1).'</div></td>';
                    $html.='<td><div class="td-content">';
                    if($sourceSearchword['items'][0][$key][0]['keywordId']!=0){
                        $html.='<a href="https://www.baidu.com/s?wd='.$sourceSearchword['items'][0][$key][0]['gbkName'].'" target="_blank" title="'.$sourceSearchword['items'][0][$key][0]['name'].'">'.$sourceSearchword['items'][0][$key][0]['name'].'</a>';
                    }else{
                        $html.=$sourceSearchword['items'][0][$key][0]['name'];
                    }
                    $html.='</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[0].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[1].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[2].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[3].'%</div></td>';
                    $html.='<td><div class="td-content text-right">'.$this->Sec2Time($value[4]).'</div></td>';
                    $html.='</tr>';
                }
                $sourceSearchword['sum'][0][3]=$sourceSearchword['sum'][0][3]=='--'?0:$sourceSearchword['sum'][0][3];
                $html.='<tr>';
                $html.='<td><div class="td-content"></div></td>';
                $html.='<td><div class="td-content">当前汇总</div></td>';
                $html.='<td><div class="td-content text-right">'.$sourceSearchword['pageSum'][0][0].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$sourceSearchword['pageSum'][0][1].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$sourceSearchword['pageSum'][0][2].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$sourceSearchword['pageSum'][0][3].'%</div></td>';
                $html.='<td><div class="td-content text-right">'.$this->Sec2Time($sourceSearchword['pageSum'][0][4]).'</div></td>';
                $html.='</tr>';
                $total=$sourceSearchword['total'];
                if($total>$max_results){
                    $page = \think\paginator\driver\Bootstrap::make(null, $max_results,$page, $total, false, ['path'=>request()->url()]);
                    $page=$this->ajax_page_memo($page,$memo);
                }else{
                    $page='';
                }
                $sum=$sourceSearchword['sum'][0];
                $sum[3]=$sum[3]=='--'?0:$sum[3];
                $sum[4]=$this->Sec2Time($sum[4]);
                $res=[
                    'status'=>1,
                    'page'=>$page,
                    'html'=>$html,
                    'sum'=>$sum
                ];
                return $res;
            }
        }
        $res=[
            'status'=>0,
            'msg'=>'暂无数据'
        ];
        return $res;
    }

    public function visitToppage(){
        $page=input("post.page")?:1;
        $memo=input("post.memo")?:'tody';
        $dateRange=$this->getStartEndDate($memo);
        $start_date=$dateRange['start_date'];
        $end_date=$dateRange['end_date'];
        $max_results=20;
        $data=$this->visit->visitToppage($page,$max_results,$start_date,$end_date);
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $result=$data['body']['data'][0]['result'];
            if($result){
                $html='';
                $list=$result['items'][1];
                foreach ($list as $key => $value) {
                    $value[3]=$value[3]=='--'?0:$value[3];
                    $html.='<tr>';
                    $html.='<td><div class="td-content">'.(20*($page-1)+$key+1).'</div></td>';
                    $html.='<td><div class="td-content">';
                    $html.='<a href="'.$result['items'][0][$key][0]['name'].'" target="_blank" title="'.$result['items'][0][$key][0]['name'].'">'.$result['items'][0][$key][0]['name'].'</a>';
                    $html.='</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[0].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[1].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[2].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[3].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[4].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[5].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[7].'%</div></td>';
                    $html.='<td><div class="td-content text-right">'.$this->Sec2Time($value[6]).'</div></td>';
                    $html.='</tr>';
                }
                $result['sum'][0][3]=$result['sum'][0][3]=='--'?0:$result['sum'][0][3];
                $html.='<tr>';
                $html.='<td><div class="td-content"></div></td>';
                $html.='<td><div class="td-content">当前汇总</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][0].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][1].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][2].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][3].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][4].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][5].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][7].'%</div></td>';
                $html.='<td><div class="td-content text-right">'.$this->Sec2Time($result['pageSum'][0][6]).'</div></td>';
                $html.='</tr>';
                $total=$result['total'];
                if($total>$max_results){
                    $page = \think\paginator\driver\Bootstrap::make(null, $max_results,$page, $total, false, ['path'=>request()->url()]);
                    $page=$this->ajax_page_memo($page,$memo);
                }else{
                    $page='';
                }
                $sum=$result['sum'][0];
                $sum[7]=$sum[7]=='--'?0:$sum[7];
                $sum[6]=$this->Sec2Time($sum[6]);
                $res=[
                    'status'=>1,
                    'page'=>$page,
                    'html'=>$html,
                    'sum'=>$sum
                ];
                return $res;
            }
        }
        $res=[
            'status'=>0,
            'msg'=>'暂无数据'
        ];
        return $res;
    }

    public function visitDistrict(){
        $memo=input("post.memo")?:'tody';
        $dateRange=$this->getStartEndDate($memo);
        $start_date=$dateRange['start_date'];
        $end_date=$dateRange['end_date'];
        $param=[
            'metrics'       =>  'pv_count,visitor_count,ip_count,bounce_ratio,avg_visit_time',
            'start_date'    =>  $start_date,
            'end_date'      =>  $end_date,
        ];
        $data=$this->visit->visitDistrict($param);
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $result=$data['body']['data'][0]['result'];
            if($result && $result['total']!=0){
                foreach ($result['items'][1] as $key => $value) {
                    $map[$key]['name']=$result['items'][0][$key][0]['name'];
                    $map[$key]['value']=$value[0];
                }
                $html='';
                $list=$result['items'][1];
                foreach ($list as $key => $value) {
                    $value[3]=$value[3]=='--'?0:$value[3];
                    $html.='<tr data-area="'.$result['items'][0][$key][0]['area'].'">';
                    $html.='<td><div class="td-content"><a href="javascript:;" class="show-district" data-key="'.$key.'"><i class="fa fa-plus" aria-hidden="true"></i></a></div></td>';
                    $html.='<td><div class="td-content">'.($key+1).'</div></td>';
                    $html.='<td><div class="td-content">';
                    $html.=$result['items'][0][$key][0]['name'];
                    $html.='</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[0].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[1].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[2].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[3].'%</div></td>';
                    $html.='<td><div class="td-content text-right">'.$this->Sec2Time($value[4]).'</div></td>';
                    $html.='</tr>';
                }
                $result['sum'][0][3]=$result['sum'][0][3]=='--'?0:$result['sum'][0][3];
                $html.='<tr>';
                $html.='<td><div class="td-content"></div></td>';
                $html.='<td><div class="td-content"></div></td>';
                $html.='<td><div class="td-content">当前汇总</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][0].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][1].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][2].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$result['pageSum'][0][3].'%</div></td>';
                $html.='<td><div class="td-content text-right">'.$this->Sec2Time($result['pageSum'][0][4]).'</div></td>';
                $html.='</tr>';
                $sum=$result['sum'][0];
                $sum[3]=$sum[3]=='--'?0:$sum[3];
                $sum[4]=$this->Sec2Time($sum[4]);
                $res=[
                    'status'=>1,
                    'html'=>$html,
                    'sum'=>$sum,
                    'map'=>$map
                ];
                return $res;
            }
        }
        $res=[
            'status'=>0,
            'msg'=>'暂无数据'
        ];
        return $res;
    }

    public function visitWorld(){
        $memo=input("post.memo")?:'tody';
        $dateRange=$this->getStartEndDate($memo);
        $start_date=$dateRange['start_date'];
        $end_date=$dateRange['end_date'];
        $data=$this->visit->visitWorld($start_date,$end_date);
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $visitWorld=$data['body']['data'][0]['result'];
            if($visitWorld && $visitWorld['total']!=0){
                foreach ($visitWorld['items'][1] as $key => $value) {
                    $map[$key]['name']=$visitWorld['items'][0][$key][0]['name'];
                    $map[$key]['value']=$value[0];
                }
                $html='';
                $list=$visitWorld['items'][1];
                foreach ($list as $key => $value) {
                    $value[3]=$value[3]=='--'?0:$value[3];
                    $html.='<tr>';
                    $html.='<td><div class="td-content">'.($key+1).'</div></td>';
                    $html.='<td><div class="td-content">';
                    $html.=$visitWorld['items'][0][$key][0]['name'];
                    $html.='</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[0].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[1].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[2].'</div></td>';
                    $html.='<td><div class="td-content text-right">'.$value[3].'%</div></td>';
                    $html.='<td><div class="td-content text-right">'.$this->Sec2Time($value[4]).'</div></td>';
                    $html.='</tr>';
                }
                $visitWorld['sum'][0][3]=$visitWorld['sum'][0][3]=='--'?0:$visitWorld['sum'][0][3];
                $html.='<tr>';
                $html.='<td><div class="td-content"></div></td>';
                $html.='<td><div class="td-content">当前汇总</div></td>';
                $html.='<td><div class="td-content text-right">'.$visitWorld['pageSum'][0][0].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$visitWorld['pageSum'][0][1].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$visitWorld['pageSum'][0][2].'</div></td>';
                $html.='<td><div class="td-content text-right">'.$visitWorld['pageSum'][0][3].'%</div></td>';
                $html.='<td><div class="td-content text-right">'.$this->Sec2Time($visitWorld['pageSum'][0][4]).'</div></td>';
                $html.='</tr>';
                $sum=$visitWorld['sum'][0];
                $sum[3]=$sum[3]=='--'?0:$sum[3];
                $sum[4]=$this->Sec2Time($sum[4]);
                $res=[
                    'status'=>1,
                    'html'=>$html,
                    'sum'=>$sum,
                    'map'=>$map
                ];
                return $res;
            }
        }
        $res=[
            'status'=>0,
            'msg'=>'暂无数据'
        ];
        return $res;
    }

    public function visitDistrictTop(){
        $memo=input("post.memo")?:'tody';
        $area=input("post.area");
        $id=input("post.id");
        $dateRange=$this->getStartEndDate($memo);
        $start_date=$dateRange['start_date'];
        $end_date=$dateRange['end_date'];
        $data=$this->visit->visitDistrictTop($start_date,$end_date,$area);
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $visitDistrictTop=$data['body']['data'][0]['result'];
            if($visitDistrictTop){
                $html='';
                $list=$visitDistrictTop['items'][1];
                $html.='<tr class="sub-line table-tr_'.$id.' sub-line-first">';
                $html.='<td class="detail"><div class="td-content"></div></td>';
                $html.='<td class="detail"><div class="td-content"></div></td>';
                $html.='<td class="sub-title detail" colspan="6">';
                $html.='<div class="td-content"><span class="icon"></span><strong>按地级市</strong></div>';
                $html.='</td>';
                $html.='</tr>';
                foreach ($list as $key => $value) {
                    $value[3]=$value[3]=='--'?0:$value[3];
                    $html.='<tr class="sub-line table-tr_'.$id.' sub-line-last">';
                    $html.='<td class="detail"><div class="td-content"></div></td>';
                    $html.='<td class="detail"><div class="td-content"></div></td>';
                    $html.='<td class="detail"><div class="td-content">';
                    $html.=$visitDistrictTop['items'][0][$key][0]['name'];
                    $html.='</div></td>';
                    $html.='<td class="detail"><div class="td-content text-right">'.$value[0].'</div></td>';
                    $html.='<td class="detail"><div class="td-content text-right">'.$value[1].'</div></td>';
                    $html.='<td class="detail"><div class="td-content text-right">'.$value[2].'</div></td>';
                    $html.='<td class="detail"><div class="td-content text-right">'.$value[3].'%</div></td>';
                    $html.='<td class="detail"><div class="td-content text-right">'.$this->Sec2Time($value[4]).'</div></td>';
                    $html.='</tr>';
                }
                $res=[
                    'status'=>1,
                    'html'=>$html
                ];
                return $res;
            }
        }
        $res=[
            'status'=>0
        ];
        return $res;
    }
    public function rankGetData(){
        $memo=input("post.memo")?:'week';
        $dateRange=$this->getStartEndDate($memo);
        $start_date=$dateRange['start_date'];
        $end_date=$dateRange['end_date'];
        $data=$this->visit->rankGetData($start_date,$end_date);
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $rankGetData=$data['body']['data'][0]['result'];
            if($rankGetData){
                foreach ($rankGetData['flash'] as $key => $value) {
                    foreach ($value['items'][0] as $ke_date => $val_date) {
                        $data[$key]['date'][$ke_date]=$val_date[0];
                    }
                    foreach ($value['items'][1] as $ke_rank => $val_rank) {
                        $data[$key]['rank'][$ke_rank]=$val_rank[0]=='--'?0:$val_rank[0];
                    }
                }
                foreach ($rankGetData['table']['items'][1] as $ke => $val) {
                    $val[5]=$this->Sec2Time($val[5]);
                    $data[$ke]['param']=$val;
                }
                $res=[
                    'status'=>1,
                    'data'=>$data
                ];
                return $res;
            }
        }
        $res=[
            'status'=>0
        ];
        return $res;
    }
    public function rankGetWords(){
        $data=$this->visit->rankGetWords();
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            $rankGetWords=$data['body']['data'][0]['result'];
            if($rankGetWords){
                $tongji_keywords=implode(",",$rankGetWords);
                set_addon_config("baiduwebtongji",['keywords'=>$tongji_keywords]);
                $res=['status'=>1,'msg'=>'同步成功'];
                return $res;
            }
        }
        $res=['status'=>0,'msg'=>'同步失败'];
        return $res;
    }
    public function rankSetWords(){
        $keywords=input('post.keywords');
        $data=$this->visit->rankSetWords($keywords);
        if($data && $data['header']['status']==0 && $data['header']['rquota']>0){
            set_addon_config("baiduwebtongji",['keywords'=>$keywords]);
            $res=['status'=>1,'msg'=>"设置成功"];
        }else{
            $res=[
                'status'=>0,
                'msg'=>$data['header']['failures'][0]['message']
            ];
        }
        return $res;
    }
    private function getStartEndDate($memo){
        switch ($memo) {
            case 'tody':
                $start_date=date("Ymd");
                $end_date=date("Ymd");
                break;
            case 'yest':
                $start_date=date("Ymd",strtotime("-1 day"));
                $end_date=date("Ymd",strtotime("-1 day"));
                break;
            case 'week':
                $start_date=date("Ymd",strtotime("-6 day"));
                $end_date=date("Ymd");
                break;
            case 'month':
                $start_date=date("Ymd",strtotime("-29 day"));
                $end_date=date("Ymd");
                break;
            default:
                $start_date=date("Ymd");
                $end_date=date("Ymd");
                break;
        }
        $result=[
            'start_date'=>$start_date,
            'end_date'=>$end_date,
        ];
        return $result;
    }
    private function switchFlag($flag){
        switch ($flag) {
            case '1':
                $class="arrow-up";
                break;
            case '0':
                $class="";
                break;
            case '-1':
                $class="arrow-down";
                break;
        }
        return $class;
    }
    /**
    * 秒格式转换为年、天、时、分、秒
    * @param int $time 秒数
    * @return string XX年XX天XX：XX：XX 
    */
    private function Sec2Time($time)
    {
        if(is_numeric($time)){
            $value = array(
                "years" => 0, "days" => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            );
            $t="";
            if($time >= '31556926'){
                $value["years"] = floor($time/'31556926');
                $time = ($time%'31556926');
                $t=$value["years"] ."年";
            }
            if($time >= '86400'){
                $value["days"] = floor($time/'86400');
                $time = ($time%'86400');
                $t.=$value["days"] ."天";
            }
            if($time >= '3600'){
                $value["hours"] = sprintf("%02d",floor($time/3600));
                $time = ($time%'3600');
                $t.=$value["hours"] .":";
            }else{
                $t.="00:";
            }
            if($time >= '60'){
                $value["minutes"] = sprintf("%02d",floor($time/60));
                $time = ($time%'60');
                $t.=$value["minutes"] .":";
            }else{
                $t.="00:";
            }
            $value["seconds"] = sprintf("%02d",floor($time));
            $t.=$value["seconds"];
            return $t;
        }else{
            return $time;
        }
    }
    private function ajax_page($page){
        return preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:;' class='ajax-page' data-page='$1'>$2</a>",$page);
    }

    private function ajax_page_memo($page,$memo){
        return preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:;' class='ajax-page' data-page='$1' data-memo='".$memo."'>$2</a>",$page);
    }
}